<?php
/***********************************************************
 * 主表文档模型
 * @作者 pcfcms <1131680521@qq.com>
 * @主页 http://www.pcfcms.com
 * @时间 2021年01月01日
***********************************************************/
namespace app\admin\model;
use think\facade\Db;
use think\facade\Cache;
use app\admin\logic\FieldLogic;
class Archives
{

    // 获取单条记录
    public function getInfo($aid, $field = null, $isshowbody = true)
    {
        $result = [];
        $field = !empty($field) ? $field : '*';
        $result = Db::name('archives')->field($field)->where('aid',$aid)->find();
        if ($isshowbody) {
            $tableName = Db::name('channel_type')->where('id',$result['channel'])->value('table');
            $result['addonFieldExt'] = Db::name($tableName.'_content')->where('aid',$aid)->find();
        }
        return $result;
    }

    // 后置操作添加|编辑自定义字段内容方法
    public function afterSave($aid, $post)
    {
        $FieldLogic = new FieldLogic();
        $post['aid'] = $aid;
        $addonFieldExt = !empty($post['addonFieldExt']) ? $post['addonFieldExt'] : [];
        $FieldLogic->PcfChannelPostData($post['channel'], $post, $addonFieldExt);
    }

    // 复制文档
    public function batch_copy($aids = [], $typeid, $channel, $num = 1)
    {
        $tableName = Db::name('channel_type')->where('id',$channel)->value('table');
        if (!empty($tableName)) {
            // 主表数据
            $archivesRow = Db::name('archives')->where('aid','IN', $aids)->select()->toArray(); 
            // 内容扩展表数据
            $tableExt = $tableName."_content";
            $contentRow = Db::name($tableExt)->where('aid','IN', $aids)->column('*', 'aid');
            foreach ($contentRow as $kk => $vv) {
                unset($contentRow[$vv['aid']]['id']);
            }
            foreach ($archivesRow as $key => $val) {
                // 同步数据
                $archivesData = [];
                for ($i = 0; $i < $num; $i++) {
                    // 主表
                    $archivesInfo = $val;
                    unset($archivesInfo['aid']);
                    $archivesInfo['typeid'] = $typeid;
                    $archivesInfo['add_time'] = getTime();
                    $archivesInfo['update_time'] = getTime();
                    $archivesData[] = $archivesInfo;
                }
                if (!empty($archivesData)) {
                    $rdata = Db::name('archives')->insertAll($archivesData);
                    $testres = Db::name('archives')->getLastInsID();
                    $ppparr = array();
                    for ($i=0; $i<$rdata; $i++) { 
                        $ppparr[] = (int)$testres++;
                    }
                    if ($ppparr) {
                        // 内容扩展表的数据
                        $contentData = [];
                        $contentInfo = $contentRow[$val['aid']];
                        // 需要复制的数据与新产生的文档ID进行关联
                        foreach ($ppparr as $k1 => $v1) {
                            $aid_new = $v1;
                            // 内容扩展表的数据
                            $contentInfo['aid'] = $aid_new;
                            $contentData[] = $contentInfo;
                        }
                        // 批量写入内容扩展表
                        if (!empty($contentData)) {
                            Db::name($tableExt)->insertAll($contentData);
                        }
                    }
                    else {
                        $result = ['status' => false, 'msg' => '复制失败！'];
                        return $result;
                    }
                }
            }
            $result = ['status' => true, 'msg' => '复制成功！'];
            return $result;
        } else {
            $result = ['status' => false, 'msg' => '模型不存在'];
            return $result;
        }
    }

    // 删除文档
    public function batch_del($del_id = [])
    {
        if (empty($del_id)) {
            $result = ['status' => 0, 'msg' => '删除ID未知'];
            return $result;
        }
        $id_arr = eyIntval($del_id);
        if(!empty($id_arr)){
            $row = Db::name('archives')
                    ->alias('a')
                    ->field('a.channel,a.aid,b.table,b.ctl_name,b.ifsystem')
                    ->join('channel_type b', 'a.channel = b.id', 'LEFT')
                    ->where('a.aid','IN', $id_arr)
                    ->select()->toArray();
            $data = [];
            foreach ($row as $key => $val) {
                $data[$val['channel']]['aid'][] = $val['aid'];
                $data[$val['channel']]['table'] = $val['table'];
                if (empty($val['ifsystem'])) {
                    $ctl_name = 'Custom';
                } else {
                    $ctl_name = $val['ctl_name'];
                }
                $data[$val['channel']]['ctl_name'] = $ctl_name;
                $data[$val['channel']]['ifsystem'] = $val['ifsystem'];
            }
            $pcferr = 0;
            foreach ($data as $key => $val) {
                $r = Db::name('archives')->where('aid','IN',$val['aid'])->delete();
                if ($r) {
                    $this->afterbatch_del($val['aid'], $val['table']);
                } else {
                    $pcferr++;
                }
            }
            if (0 == $pcferr) {
                $result = ['status' => 1, 'msg' => '删除成功'];
                return $result;
            } else if ($pcferr < count($data)) {
                $result = ['status' => 0, 'msg' => '删除部分成功'];
                return $result;
            } else {
                $result = ['status' => 0, 'msg' => '删除失败'];
                return $result;
            }
        }else{
            $result = ['status' => 0, 'msg' => '文档不存在'];
            return $result;
        }
    }

    // 后置操作删除的方法
    public function afterbatch_del($aid = [], $tableName)
    {
        if (is_string($aid)) {
            $aid = explode(',', $aid);
        }
        // 同时删除文档表
        Db::name('archives')->where('aid','IN', $aid)->delete();
        // 同时删除内容表
        Db::name($tableName.'_content')->where('aid','IN', $aid)->delete();
    }

    // 后置操作删除的方法
    public function afterDel($typeidArr = [], $channel)
    {
        if (is_string($typeidArr)) {
            $typeidArr = explode(',', $typeidArr);
        }
        // 同时删除文档表
        Db::name('archives')->where('typeid','IN', $typeidArr)->delete();
        $tableName = Db::name('channel_type')->where('id',$channel)->value('table');
        // 同时删除内容表
        Db::name($tableName.'_content')->where('typeid','IN', $typeidArr)->delete();
        // 清除缓存
        Cache::delete("arctype");
        Cache::delete('admin_archives_release');
    }

    // 获取文档模板文件列表
    public function getTemplateList($nid = "article")
    {
        $tpl_theme = config('pcfcms.admin_config.tpl_theme');
        $planPath = WWW_ROOT."public/template/{$tpl_theme}/pc";
        $dirRes   = opendir($planPath);
        $view_suffix = config('template.view_suffix') ? config('template.view_suffix') : 'html';
        // 模板PC目录文件列表
        $templateArr = [];
        while($filename = readdir($dirRes)){
            if (in_array($filename, array('.','..'))) {
                continue;
            }
            array_push($templateArr, $filename);
        }
        $templateList = [];
        foreach ($templateArr as $k2 => $v2) {
            $v2 = iconv('GB2312', 'UTF-8', $v2);
            preg_match('/^(view)_'.$nid.'(_(.*))?\.'.$view_suffix.'/i', $v2, $matches1);
            if (!empty($matches1)) {
                if ('view' == $matches1[1]) {
                    array_push($templateList, $v2);
                }
            }
        }
        return $templateList;
    }

}